package com.xds.gulimall.product.exception;

import com.baomidou.mybatisplus.annotation.TableField;
import com.xds.common.exception.BizCode;
import com.xds.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理异常
 * @author : baixu
 * @date : 10:58 2021/11/16
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.xds.gulimall.product.controller")
public class GulimallExceptionAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass());
        Map<String,String> map=new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach((item)->{
            map.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCode.VALID_EXCEPTION.getCode(),BizCode.VALID_EXCEPTION.getMeg()).put("data",map);

    }
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e){
        log.error("错误异常{}",e);
        return R.error(BizCode.UNKNOW_EXCEPYION.getCode(), BizCode.UNKNOW_EXCEPYION.getMeg());
    }
}
